package cit.project.capeclear;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import android.content.Context;
import android.util.Log;
import android.widget.LinearLayout;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalAdvancedPayment;
import com.paypal.android.MEP.PayPalInvoiceData;
import com.paypal.android.MEP.PayPalInvoiceItem;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.PayPalReceiverDetails;

public class Payment {

	protected static final int INITIALIZE_SUCCESS = 0;
	protected static final int INITIALIZE_FAILURE = 1;

	
	private PayPal ppObj = null;
	
	//PayPal App ID, when using ENV_NONE server is not needed
	private static String appID = "none"; 
	//Paypal server to use (NONE/SANDBOX/LIVE)
	private static int ppServer = PayPal.ENV_NONE; 
	
	//Booking Payment information
	public boolean shipping = false;
	public String recipientMail = "";
	public String paymentSubtotal = "0";
	private int paymentType = PayPal.PAYMENT_TYPE_GOODS;
	public String storeName = "";
	public String itemName = "";
	public String unitPrice = "0";
	public int quantity = 1;
	public String paymentMemo = "Payment made with Cape Clear App for Android.";

	//Payment objects for Shop
	public Vector<Item> items;
	public Map<String, String> shopMap;
	public Map<String, PayPalReceiverDetails> ppReceiversMap;
	public Map<String, PayPalInvoiceData> ppInvoicesMap;
	private Map<String, Float> shopSubTotal;
	private Vector<String> shopNames;
	private float shippingPrice = 5;
	
	//Payment button
	CheckoutButton launchPayment;
	
	private Context ctx;
	
	public Payment (Context context)
	{
		ctx = context;
	}
	
	/**
	 * The initLibrary function takes care of all the basic Library initialization.
	 * @param thread 
	 * 
	 * @return The return will be true if the initialization was successful and false if 
	 */
	void initLibrary() {
		// If the library is already initialized, then we don't need to initialize it again.
		if(ppObj == null) {
			// This is the main initialization call that takes in your Context, the Application ID, and the server you would like to connect to.
			ppObj = PayPal.initWithAppID(ctx, appID, ppServer);
   			
			// -- These are required settings.
			ppObj.setLanguage("en_GB"); // Sets the language for the library.
        	// --
        	
        	// -- These are a few of the optional settings.
        	// Sets the fees payer. If there are fees for the transaction, this person will pay for them. Possible values are FEEPAYER_SENDER,
        	// FEEPAYER_PRIMARYRECEIVER, FEEPAYER_EACHRECEIVER, and FEEPAYER_SECONDARYONLY.
			ppObj.setFeesPayer(PayPal.FEEPAYER_SENDER); 
        	// Set to true if the transaction will require shipping.
			ppObj.setShippingEnabled(shipping);
        	// Dynamic Amount Calculation allows you to set tax and shipping amounts based on the user's shipping address. Shipping must be
        	// enabled for Dynamic Amount Calculation. This also requires you to create a class that implements PaymentAdjuster and Serializable.
			ppObj.setDynamicAmountCalculationEnabled(false);
        	// --
		}
	}

	
	public boolean isLibraryInitialized ()
	{
		return PayPal.getInstance().isLibraryInitialized();
	}

	/**
	 * Create our CheckoutButton and update the UI.
	 * @return 
	 */
	public CheckoutButton setupButton() {
		
		
		// Get the CheckoutButton. 
		launchPayment = ppObj.getCheckoutButton(ctx, PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
		
		return launchPayment;		

	}
	

	/**
	 * Create a PayPalPayment which is used for booking payments.
	 * 
	 * @return Returns a PayPalPayment. 
	 */
	PayPalPayment simplePayment() {
		    	
		// Create a basic PayPalPayment.
		PayPalPayment payment = new PayPalPayment();
		// Sets the currency type for this payment.
		payment.setCurrencyType("EUR");
		// Sets the recipient for the payment. This can also be a phone number.
		payment.setRecipient(recipientMail);
		// Sets the amount of the payment, not including tax and shipping amounts.
		payment.setSubtotal(new BigDecimal(paymentSubtotal));
		// Sets the payment type. This can be PAYMENT_TYPE_GOODS, PAYMENT_TYPE_SERVICE, PAYMENT_TYPE_PERSONAL, or PAYMENT_TYPE_NONE.
		payment.setPaymentType(paymentType);
		
		// PayPalInvoiceData can contain tax and shipping amounts. It also contains an ArrayList of PayPalInvoiceItem which can
		// be filled out. These are not required for any transaction.
		PayPalInvoiceData invoice = new PayPalInvoiceData();
		
		// PayPalInvoiceItem has several parameters available to it. None of these parameters is required.
		PayPalInvoiceItem item1 = new PayPalInvoiceItem();
		// Sets the name of the item.
		item1.setName(itemName);
		// Sets the total price which should be (quantity * unit price). The total prices of all PayPalInvoiceItem should add up
		// to less than or equal the subtotal of the payment.
		item1.setTotalPrice(new BigDecimal(paymentSubtotal));
		// Sets the unit price.
		item1.setUnitPrice(new BigDecimal(unitPrice));
		// Sets the quantity.
		item1.setQuantity(quantity);
		// Add the PayPalInvoiceItem to the PayPalInvoiceData. Alternatively, you can create an ArrayList<PayPalInvoiceItem>
		// and pass it to the PayPalInvoiceData function setInvoiceItems().
		invoice.getInvoiceItems().add(item1);
		
		
		// Sets the PayPalPayment invoice data.
		payment.setInvoiceData(invoice);
		// Sets the merchant name. This is the name of your Application or Company.
		payment.setMerchantName(storeName);
    	// Sets the memo. This memo will be part of the notification sent by PayPal to the necessary parties.
    	payment.setMemo(paymentMemo);
    	
		return payment;

    	
	}

	
	/**
	 * Create a PayPalAdvancedPayment is setup to be a parallel payment.
	 * 
	 * @return Returns a PayPalAdvancedPayment.
	 */
	public PayPalAdvancedPayment parallelPayment() {
		// Create the PayPalAdvancedPayment.
		PayPalAdvancedPayment payment = new PayPalAdvancedPayment();
		// Sets the currency type for this payment.
    	payment.setCurrencyType("EUR");
    	// Sets the memo. This memo will be part of the notification sent by PayPal to the necessary parties.
    	payment.setMemo(paymentMemo);
    	
    	
    	ppReceiversMap = new HashMap<String, PayPalReceiverDetails>();
    	ppInvoicesMap = new HashMap<String, PayPalInvoiceData>();
    	shopSubTotal = new HashMap<String, Float>();
    	shopNames = new Vector<String>();
    	
    	// Creates all the PayPalReceiverDetails for the required payments.
    	for (int i=0; i<items.size(); i++)
    	{
    		Item item = items.elementAt(i);
    		String shopName = item.shopName;
    		PayPalInvoiceData ppi;
    		
    		
    		// If the shop still doesn't have a PayPalReceiverDetails object, creates and adds it to ppReceiversMap
    		if (!ppReceiversMap.containsKey(shopName))
			{
    			Log.v("x", "Iter: "+i+" shop name: " + shopName);
    			shopNames.add(shopName);
    			
        		PayPalReceiverDetails ppr = new PayPalReceiverDetails();
        		ppr.setRecipient(shopMap.get(shopName));
        		ppr.setMerchantName(shopName);
        		ppr.setIsPrimary(false); // In a parallel payment no one of the recipients is primary
        		
        		shopSubTotal.put(shopName, (float) 0);
        		ppReceiversMap.put(shopName, ppr);
			}
    		
    		// If the shop still doesn't have a PayPalInvoiceData object, creates and adds it to ppInvoicesMap
    		if (!ppInvoicesMap.containsKey(shopName))
			{
    			ppi = new PayPalInvoiceData();
    			ppi.setTax(new BigDecimal("0.00"));
			}
    		else
    			ppi = ppInvoicesMap.get(shopName);
    		
    		// Addition of the item to the invoice.
    		PayPalInvoiceItem ppItem = new PayPalInvoiceItem();
    		ppItem.setName(item.title);
    		ppItem.setID(item.code+"");
    		ppItem.setTotalPrice(new BigDecimal(item.price*item.quantity));
    		ppItem.setUnitPrice(new BigDecimal(item.price));
    		ppItem.setQuantity(item.quantity);
    		
    		if (item.shipment == 1)
    			ppi.setShipping(new BigDecimal(shippingPrice));
    		
        	ppi.getInvoiceItems().add(ppItem);
        	ppInvoicesMap.put(shopName, ppi);
        	
			Log.v("x", "Price: " + item.price + " Total price: " + (item.price * item.quantity));

        	Float st = shopSubTotal.get(shopName);
        	st = st + (item.price * item.quantity);
        	shopSubTotal.put(shopName, st);
        	

    	}
    	
    	
    	for (int i = 0; i < shopNames.size(); i++)
    	{
    		PayPalReceiverDetails ppr = ppReceiversMap.get(shopNames.elementAt(i));
    		
    		ppr.setSubtotal(new BigDecimal( shopSubTotal.get(shopNames.elementAt(i))) );
    		ppr.setInvoiceData(ppInvoicesMap.get(shopNames.elementAt(i)));
    		
    		payment.getReceivers().add(ppr);
    	}
    	
    	return payment;

    	
	}


}
